import { createApp } from 'vue'
import { createPinia } from 'pinia'
import piniaPersist from 'pinia-plugin-persistedstate'

import App from './App.vue'
import router from './router'

import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import axios from 'axios'

//拦截用户的每一次请求：在请求上自动加Authorization（如果存在token）
axios.interceptors.request.use(config => {
    const token = localStorage.getItem('token')
    console.log("vue 拦截器 这次请求 携带 token:" + token)
    if (token) {
        config.headers.Authorization = `Bearer ${token}`
        console.log("最终的请求头：", config.headers)
    }
    return config
}, err => Promise.reject(err))
// （建议加上）全局响应拦截器：处理 401 未登录
axios.interceptors.response.use(
  res => res,
  err => {
    if (err.response && err.response.status === 401) {
      const confirmed = window.confirm('登录状态已过期，请重新登录。点击确定跳转登录，取消返回首页。')
       // token过期或无效
      localStorage.removeItem("token")
      localStorage.removeItem("userId")
      localStorage.removeItem("userName")
      if (confirmed) {
        router.push('/login')
      } else {
        router.push('/')
      }
    }
    return Promise.reject(err)
  }
)

const app = createApp(App)

// app.use(createPinia())
app.use(router)
const pinia = createPinia()
pinia.use(piniaPersist)
app.use(pinia)
app.use(ElementPlus)

app.mount('#app')